<template>
  <div class="table-box">
    <div>
      <table>
        <tr>
          <td>连接状态:</td>
          <td v-if="linkStatus == true"><p style="padding: 0 8px; color: #00aa00">连接成功</p></td>
          <td v-if="linkStatus == false"><p style="padding: 0 8px; color: #ff0000">连接失败</p></td>
          <td v-if="showIpandPort == true">PPBX的IP和端口:</td>
          <td v-if="showIpandPort == true"><el-input v-model="form.ipAndPort" placeholder="请输入PPBX的IP和端口" /></td>
          <td v-if="showIpandPort == true">账户:</td>
          <td v-if="showIpandPort == true"><el-input v-model="form.username" placeholder="请输入账户" /></td>
          <td v-if="showIpandPort == true">密码:</td>
          <td v-if="showIpandPort == true"><el-input v-model="form.password" type="password" placeholder="请输入密码" /></td>

          <td v-if="showIpandPort == true">
            <el-button type="primary" link @click="checkAndSave">校验并保存</el-button>
          </td>
          <td v-if="showIpandPort == true">
            <el-button type="primary" link @click="checkLink">测试连接</el-button>
          </td>
        </tr>
      </table>
    </div>
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" plain @click="EditGroup(scope.selectedList)">回访</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      表格操作
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="EditGroup([scope.row])">回访</el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { User, RoleManager, dataDictionary } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/dataDictionary/groupManagement/components/groupDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  changeUserStatus,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser
} from "@/api/modules/user";
import { getPpbxToken } from "@/api/modules/index";
import { findNoticeRulePager, delNoticeRules } from "@/api/modules/systemTools";
import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import { dataDictionaryGroupFind, deleteGroup, exportDataDictionaryGroup } from "@/api/modules/dataDictionary";
import {
  findCallLogPage,
  updateFollowStatusByIds,
  saveAndCheck,
  getPpbxIpAndPortUsernamePassword
} from "@/api/modules/callAgent";
import WebSocket from "@/api/modules/websocket";
import { useUserStore } from "@/stores/modules/user";
const route = useRoute();
const router = useRouter();

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行

const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
const form = ref({
  ipAndPort: "",
  username: "",
  password: ""
});
const linkStatus = ref(true);
const checkAndSave = (data: any) => {
  if (form.value.ipAndPort == "") {
    ElMessage.error("请输入ip端口");
    return;
  }
  if (form.value.username == "") {
    ElMessage.error("请输入用户名");
    return;
  }
  if (form.value.password == "") {
    ElMessage.error("请输入密码");
    return;
  }
  console.log("ssssss");
  saveAndCheck(form.value, "ppbxTokenDTO").then(res => {
    if (res != null) {
      let newParams = JSON.parse(res.toString());

      if (newParams.code != 0) {
        ElMessage.info(newParams.message);
      } else {
        ElMessage.info(newParams.message);
      }
    }

    console.log(res);
  });
};

const checkLink = () => {
  let webSocketUrl = "ws://192.168.1.203:8889/api/buletooth";
  getPpbxToken().then(res => {
    if (res != null && res != undefined) {
      let jsondata = JSON.parse(res.toString());
      let token = "";
      let ipAndPort = "";
      token = jsondata.token;
      ipAndPort = jsondata.ipAndPort;
      console.log(token);
      console.log(ipAndPort);
      webSocketUrl = "wss://" + ipAndPort + "/openapi/v1.0/subscribe?access_token=" + token;
      WebSocket.webSocketInit(webSocketUrl); //初始化webSocket

      WebSocket.setOpenCallback(res => {
        linkStatus.value = true;
        ElMessage.success("连接成功");
        console.log("连接建立成功", res);
      });

      WebSocket.setCloseCallback(res => {
        linkStatus.value = false;
        ElMessage.info("连接失败");
        console.log("连接关闭", res);
      });
      WebSocket.setErrorCallback(res => {
        linkStatus.value = false;
        // ElMessage.info("连接失败");
        // WebSocket.webSocketInit(webSocketUrl);
        // console.log("连接发生错误", res);
      });
    } else {
      linkStatus.value = false;
    }
  });
};
const showIpandPort = ref(false);
onMounted(() => {
  //请求分类选择树
  console.log("onmound");
  getPpbxIpAndPortUsernamePassword().then(res => {
    if (res != undefined && res != null) {
      let newParams = JSON.parse(res.toString());
      form.value.ipAndPort = newParams.ipAndPort;
      form.value.username = newParams.username;
      form.value.password = newParams.password;
    }
    console.log(res);
  });
  checkLink();
  // setInterval(()=> {
  // 		console.log("执行校验连接")

  // 		// 在这里写定时器执行的代码
  // 	}, 40000);
  const userStore = useUserStore();
  if (userStore.username == "admin") {
    showIpandPort.value = true;
  }
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "callTime";
  newParams.sord = "desc";
  if (newParams.createTime != undefined) {
    newParams.callTimeStart = newParams.createTime[0];
    newParams.callTimeEnd = newParams.createTime[1];
    delete newParams.createTime;
  }
  delete newParams.pageNum;
  delete newParams.pageSize;
  return findCallLogPage(newParams, "callLogQueryDTO", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};
export interface resList {
  callTime: string;
  companyNo: string;
  createTime: string;
  creator: string;
  custName: string;
  dataFlag: string;
  description: string;
  followName: string;
  id: string;
  indexContent: string;
  isFollow: number;
  lastUpdateTime: string;
  lastUpdater: string;
  operId: string;
  optimisticLock: string;
  phone: string;
  remark: string;
  ringTime: string;
  status: number;
  uid: string;
}
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "custName", label: "名称", search: { el: "input" }, sortable: true, width: 80 },
  { prop: "phone", label: "来电号码", search: { el: "input" }, sortable: true },
  { prop: "operId", label: "分机号", search: { el: "input" }, sortable: true },
  {
    prop: "createTime",
    label: "来电时间",
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" }
    },
    sortable: true
  },
  { prop: "ringTime", label: "振铃时间（秒）", sortable: true },
  { prop: "status", label: "状态", sortable: true, render: scope => <>{scope.row.status === 0 ? "未接" : "已接"}</> },

  {
    prop: "isFollow",
    label: "是否回访",
    sortable: true,
    width: 122,
    enum: [
      {
        genderLabel: "已回访",
        genderValue: "1"
      },
      {
        genderLabel: "未回访",
        genderValue: "0"
      }
    ],
    fieldNames: { label: "genderLabel", value: "genderValue" },
    search: { el: "select", props: { filterable: true } },
    render: scope => <>{scope.row.isFollow === 0 ? "未回访" : "已回访"}</>
  },
  { prop: "followName", label: "回访人", search: { el: "input" }, sortable: true },

  { prop: "operation", label: "操作项", fixed: "right", width: 160 }
]);
const addTemplate = () => {
  router.push(`/system/tools/addNotificationTemplate?pageNo=${Math.random().toFixed(3)}`);
};
// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除
const deleteAccount = async (params: resList) => {
  batchDelete([params]);
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 批量删除
const batchDelete = async (id: any[]) => {
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?ids=" + id[i].noticeRuleId;
    } else {
      idsStr = idsStr + "&ids=" + id[i].noticeRuleId;
    }
    NameStr = NameStr + id[i].noticeRuleName + ",";
  }
  ElMessageBox.confirm("是否删除选中的数据：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      //await useHandleData(deleteUser, { id }, "删除所选用户信息");
      delNoticeRules(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const EditGroup = async (id: any[]) => {
  if (id.length == 0) {
    ElMessage.error("至少选择一条数据");
    return;
  }
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?ids=" + id[i].id;
    } else {
      idsStr = idsStr + "&ids=" + id[i].id;
    }
    NameStr = NameStr + id[i].custName + ",";
  }
  ElMessageBox.confirm("是否回访选中的客户：" + NameStr + " ？", "回访确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      //await useHandleData(deleteUser, { id }, "删除所选用户信息");
      updateFollowStatusByIds(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: "回访成功"
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消回访"
      });
    });
};
</script>
